/*
 *  (C) Copyright 2008 Insula T.I. Ltda.
 * 
 *  This file is part of Vulcano.
 *
 *  Vulcano is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Vulcano is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Vulcano.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.openinsula.vulcano.orm.dao.hibernate;

import java.util.List;

import org.openinsula.vulcano.orm.dao.Dao;
import org.openinsula.vulcano.orm.dao.query.DaoQuery;
import org.openinsula.vulcano.orm.dao.query.DaoQueryVisitor;
import org.openinsula.vulcano.orm.dao.query.DistinctDaoQuery;
import org.openinsula.vulcano.orm.dao.query.ProjectionDaoQuery;
import org.openinsula.vulcano.orm.dao.query.SimpleDaoQuery;

/**
 * @author rebola
 * @author yanaga
 * @since 1.1
 * @see Dao
 * @see DaoQuery
 * @see HibernateDao
 */
public class OrderHqlDaoQueryVisitor implements DaoQueryVisitor<String> {

	public String visit(final DistinctDaoQuery<?> distinctDaoQuery) {
		return createOrderClause(distinctDaoQuery);
	}

	public String visit(final ProjectionDaoQuery<?> projectionDaoQuery) {
		return "";
	}

	public String visit(final SimpleDaoQuery<?> simpleDaoQuery) {
		return createOrderClause(simpleDaoQuery);
	}

	private String createOrderClause(final DaoQuery<?> daoQuery) {
		List<String> orderParameters = daoQuery.getOrderParameters();

		if (orderParameters == null || orderParameters.size() == 0) {
			return "";
		}

		StringBuilder sb = new StringBuilder();

		sb.append(" order by ");
		sb.append(HibernateDao.QUERY_ALIAS);
		sb.append('.');
		sb.append(orderParameters.get(0));

		for (int i = 1; i < orderParameters.size(); i++) {
			sb.append(", ");
			sb.append(HibernateDao.QUERY_ALIAS);
			sb.append('.');
			sb.append(orderParameters.get(i));
		}

		return sb.toString();
	}

}
